package com.hzlx.config;

import jakarta.annotation.Resource;
import org.junit.jupiter.api.Order;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.Ordered;
import org.springframework.security.config.Customizer;
import org.springframework.security.config.web.server.SecurityWebFiltersOrder;
import org.springframework.security.config.web.server.ServerHttpSecurity;
import org.springframework.security.web.server.SecurityWebFilterChain;
import org.springframework.security.web.server.context.NoOpServerSecurityContextRepository;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.reactive.CorsWebFilter;
import org.springframework.web.cors.reactive.UrlBasedCorsConfigurationSource;
import reactor.core.publisher.Mono;

@Configuration
public class SecurityConfig {

    @Resource
    AccessReactiveAuthorizationManager accessReactiveAuthorizationManager;
    @Resource
    TokenFilter tokenFilter;
    @Bean
    public SecurityWebFilterChain securityWebFilterChain(ServerHttpSecurity http) {
        return http
                .cors(Customizer.withDefaults())
                .csrf(csrfSpec -> csrfSpec.disable())
                .httpBasic(httpBasicSpec -> httpBasicSpec.disable())
                .formLogin(formLoginSpec -> formLoginSpec.disable())
                // 禁用 Spring Security 内部的认证机制
                .authenticationManager(authenticationManager -> Mono.empty())
                .securityContextRepository(NoOpServerSecurityContextRepository.getInstance())
//                .addFilterAt(corsFilter(), SecurityWebFiltersOrder.FIRST)
//                .addFilterAt(tokenFilter, SecurityWebFiltersOrder.AUTHENTICATION)
//                // 配置授权规则
//                .authorizeExchange(ex ->
//                        ex.pathMatchers("/auth/login").permitAll()
//                                .pathMatchers("/api/menus").permitAll()
//                                .anyExchange().access(accessReactiveAuthorizationManager)
//                )
                .build();
    }

    @Bean
    public CorsWebFilter corsFilter(){                          // 定制跨域共享过滤器
        CorsConfiguration config = new CorsConfiguration();
        config.addAllowedOrigin("http://localhost:5173");                        // 允许任何域
        config.addAllowedMethod("*");                        // 允许任何方法
        config.addAllowedHeader("*");                        // 允许任何请求头
        config.addExposedHeader("Authorization");            // 对外暴露Authorization头
        config.setAllowCredentials(true);
        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        source.registerCorsConfiguration("/**",config);
        return new CorsWebFilter(source);
    }
}
